package com.example.withroadlogistics.loginui;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.withroadlogistics.BMapApiDemoMain;
import com.example.withroadlogistics.R;
import com.example.withroadlogistics.model.User;
import com.example.withroadlogistics.until.HttpCallbackListener;
import com.example.withroadlogistics.until.HttpUtil;
import com.example.withroadlogistics.until.MySharedPreferences;
import com.example.withroadlogistics.until.constant;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnFocusChangeListener, ViewTreeObserver.OnGlobalLayoutListener, TextWatcher {
    private String TAG = "ifu25";
    private ImageButton mIbNavigationBack;
    private RadioButton admin, user;
    private EditText mEtLoginUsername;
    private EditText mEtLoginPwd;
    private LinearLayout mLlLoginUsername;
    private ImageView mIvLoginUsernameDel;
    private Button mBtLoginSubmit;
    private LinearLayout mLlLoginPwd;
    private ImageView mIvLoginPwdDel;
    private ImageView mIvLoginLogo;
    private LinearLayout mLayBackBar;
    private TextView mTvLoginForgetPwd;
    private Button mBtLoginRegister;
    //全局Toast
    private Toast mToast;
    private int mLogoHeight;
    private int mLogoWidth;

    //private String originAddress = "http://192.168.1.2:8080/PowerManage/Login";//servlet地址
   // private String originAddress = "http://192.168.43.221:8080/PowerManage/user/userlogin";//controler地址
    //private String originAddress = "http://localhost:8080/TransportManage_war_exploded/user/userlogin";
    //private String originAddress = "http://192.168.1.104:8080/TransportManage_war_exploded/user/userlogin";
    private String originAddress = constant.url+"user/userlogin";
    //    Handler是Android SDK来处理异步消息的核心类。
//    子线程与主线程通过Handler来进行通信。子线程可以通过Handler来通知主线程进行UI更新。
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = "";

            if ("OK".equals(msg.obj.toString())){
                result = "success";
            }else if ("Wrong".equals(msg.obj.toString())){
                result = "fail";
            }else {
                String data = msg.obj.toString();
//            	Toast.makeText(MainActivity.this, data, Toast.LENGTH_LONG).show();
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String code = jsonObject.getString("code");
                   // if (code.equals("1")) {
                        if (code.equals("0")) {
                       // result = jsonObject.getString("data");
                        //web端返回的json code data
                        Log.i(TAG, "handleMessage: wen端返回的json"+code+data+result);
                        //通过Bundle封装数据
                        Bundle bundle = new Bundle();
                       // bundle.putString("data", result);//data是通过后台返回数值进行判断，弹窗
                        //通过Intent控制Activity跳转
                        Intent intent = new Intent();
                        intent.setClass(MainActivity.this, BMapApiDemoMain.class);//成功跳转
                        intent.putExtras(bundle);
                        finish();
                        startActivity(intent);
                    }else {
                      //  result = jsonObject.getString("data");
                        Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();//失败提示
                        Toast.makeText(MainActivity.this, "账号或用户名输入错误", Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(MainActivity.this, "账号或用户名输入错误", Toast.LENGTH_LONG).show();
                }
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_login);
        initView();

        mBtLoginSubmit = (Button)findViewById(R.id.bt_login_submit);
        //获取用户名的id
        mEtLoginUsername = (EditText)findViewById(R.id.et_login_username);
        //获取密码的id
        mEtLoginPwd = (EditText)findViewById(R.id.et_login_pwd);


    }


    //初始化视图
    private void initView() {
             //导航栏+返回按钮
        mLayBackBar = findViewById(R.id.ly_retrieve_bar);
        mIbNavigationBack = findViewById(R.id.ib_navigation_back);
        //logo
        mIvLoginLogo = findViewById(R.id.iv_login_logo);
        //username
        mLlLoginUsername = findViewById(R.id.ll_login_username);
        mEtLoginUsername = findViewById(R.id.et_login_username);
        mIvLoginUsernameDel = findViewById(R.id.iv_login_username_del);
        //passwd
        mLlLoginPwd = findViewById(R.id.ll_login_pwd);
        mEtLoginPwd = findViewById(R.id.et_login_pwd);
        mIvLoginPwdDel = findViewById(R.id.iv_login_pwd_del);
        //提交、注册
       mBtLoginSubmit = findViewById(R.id.bt_login_submit);
        mBtLoginRegister = findViewById(R.id.bt_login_register);
        //忘记密码
        mTvLoginForgetPwd = findViewById(R.id.tv_login_forget_pwd);
        mTvLoginForgetPwd.setOnClickListener(this);
        //注册点击事件
       mIbNavigationBack.setOnClickListener(this);
        mEtLoginUsername.setOnClickListener(this);
        mIvLoginUsernameDel.setOnClickListener(this);
       mBtLoginSubmit.setOnClickListener(this);
        mBtLoginRegister.setOnClickListener(this);
        mEtLoginPwd.setOnClickListener(this);
        mIvLoginPwdDel.setOnClickListener(this);
               //注册其它事件
        mLayBackBar.getViewTreeObserver().addOnGlobalLayoutListener(this);
        mEtLoginUsername.setOnFocusChangeListener(this);
        mEtLoginUsername.addTextChangedListener(this);
        mEtLoginPwd.setOnFocusChangeListener(this);
        mEtLoginPwd.addTextChangedListener(this);
        //角色
        admin = (RadioButton)findViewById(R.id.admin);
        user = (RadioButton)findViewById(R.id.user);
    }

    private boolean isInputValid() {
        //检查用户输入的合法性，这里暂且默认用户输入合法
        return true;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_navigation_back:
                //返回
                finish();
                break;
            case R.id.et_login_username:
                mEtLoginPwd.clearFocus();
                mEtLoginUsername.setFocusableInTouchMode(true);
                mEtLoginUsername.requestFocus();
                break;
            case R.id.et_login_pwd:
                mEtLoginUsername.clearFocus();
                mEtLoginPwd.setFocusableInTouchMode(true);
                mEtLoginPwd.requestFocus();
                break;
            case R.id.iv_login_username_del:
                //清空用户名
                mEtLoginUsername.setText(null);
                break;
            case R.id.iv_login_pwd_del:
                //清空密码
                mEtLoginPwd.setText(null);
                break;
            case R.id.bt_login_submit:
                //登录
                login();
//                Intent intent = new Intent();
//                intent.setClass(MainActivity.this, BMapApiDemoMain.class);//成功跳转
//                startActivity(intent);
                break;
            case R.id.bt_login_register:
                //注册
                startActivity(new Intent(MainActivity.this, RegisterActivity.class));
                break;
            case R.id.tv_login_forget_pwd:
                //忘记密码
                startActivity(new Intent(MainActivity.this, ForgetPwdActivity.class));
                break;
        }
    }

    //用户名密码焦点改变
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int id = v.getId();

        if (id == R.id.et_login_username) {
            if (hasFocus) {
                mLlLoginUsername.setActivated(true);
                mLlLoginPwd.setActivated(false);
            }
        } else {
            if (hasFocus) {
                mLlLoginPwd.setActivated(true);
                mLlLoginUsername.setActivated(false);
            }
        }
    }



    //显示或隐藏logo
    @Override
    public void onGlobalLayout() {
        final ImageView ivLogo = this.mIvLoginLogo;
        Rect KeypadRect = new Rect();

        mLayBackBar.getWindowVisibleDisplayFrame(KeypadRect);

        int screenHeight = mLayBackBar.getRootView().getHeight();
        int keypadHeight = screenHeight - KeypadRect.bottom;

        //隐藏logo
        if (keypadHeight > 300 && ivLogo.getTag() == null) {
            final int height = ivLogo.getHeight();
            final int width = ivLogo.getWidth();
            this.mLogoHeight = height;
            this.mLogoWidth = width;

            ivLogo.setTag(true);

            ValueAnimator valueAnimator = ValueAnimator.ofFloat(1, 0);
            valueAnimator.setDuration(400).setInterpolator(new DecelerateInterpolator());
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float animatedValue = (float) animation.getAnimatedValue();
                    ViewGroup.LayoutParams layoutParams = ivLogo.getLayoutParams();
                    layoutParams.height = (int) (height * animatedValue);
                    layoutParams.width = (int) (width * animatedValue);
                    ivLogo.requestLayout();
                    ivLogo.setAlpha(animatedValue);
                }
            });

            if (valueAnimator.isRunning()) {
                valueAnimator.cancel();
            }
            valueAnimator.start();
        }
        //显示logo
        else if (keypadHeight < 300 && ivLogo.getTag() != null) {
            final int height = mLogoHeight;
            final int width = mLogoWidth;

            ivLogo.setTag(null);

            ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
            valueAnimator.setDuration(400).setInterpolator(new DecelerateInterpolator());
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float animatedValue = (float) animation.getAnimatedValue();
                    ViewGroup.LayoutParams layoutParams = ivLogo.getLayoutParams();
                    layoutParams.height = (int) (height * animatedValue);
                    layoutParams.width = (int) (width * animatedValue);
                    ivLogo.requestLayout();
                    ivLogo.setAlpha(animatedValue);
                }
            });

            if (valueAnimator.isRunning()) {
                valueAnimator.cancel();
            }
            valueAnimator.start();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    //用户名密码输入事件
    @Override
    public void afterTextChanged(Editable s) {
        String username = mEtLoginUsername.getText().toString().trim();
        String pwd = mEtLoginPwd.getText().toString().trim();

        //是否显示清除按钮
        if (username.length() > 0) {
            mIvLoginUsernameDel.setVisibility(View.VISIBLE);
        } else {
            mIvLoginUsernameDel.setVisibility(View.INVISIBLE);
        }
        if (pwd.length() > 0) {
            mIvLoginPwdDel.setVisibility(View.VISIBLE);
        } else {
            mIvLoginPwdDel.setVisibility(View.INVISIBLE);
        }

        //登录按钮是否可用
        if (!TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(username)) {
            mBtLoginSubmit.setBackgroundResource(R.drawable.bg_login_submit);
            mBtLoginSubmit.setTextColor(getResources().getColor(R.color.white));
        } else {
            mBtLoginSubmit.setBackgroundResource(R.drawable.bg_login_submit_lock);
            mBtLoginSubmit.setTextColor(getResources().getColor(R.color.account_lock_font_color));
        }
    }

    //登陆
    public void login() {
        //取得用户输入的账号和密码
        if (!isInputValid()){
            return;
        }
        String userid = mEtLoginUsername.getText().toString().trim();
        String pwd = mEtLoginPwd.getText().toString().trim();
        if (userid.isEmpty()) {
            Toast.makeText(MainActivity.this, "账号不能为空！", Toast.LENGTH_LONG).show();
            return;
        }else if (pwd.isEmpty()) {
            Toast.makeText(MainActivity.this, "密码不能为空！", Toast.LENGTH_LONG).show();
            return;
        }
//        else if (!admin.isChecked() && !user.isChecked()) {
//            Toast.makeText(MainActivity.this, "请选择权限！", Toast.LENGTH_LONG).show();
//            return;
//        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put(User.USERID, userid);
        params.put(User.PWD, pwd);
        //权限判断
//        if (admin.isChecked()) {
//            params.put(User.ROLEID, "1");
//        }else if (user.isChecked()) {
//            params.put(User.ROLEID, "4");
//        }

        //验证成功后在 MySharedPreferences类里定义好存取方法后，就可以调用了
        //这里将数据保存进去  注意：(userid 我是定义了有返回值的，试试看)
        Boolean bool = MySharedPreferences.setUserid(userid, MainActivity.this);
        MySharedPreferences.setPwd(pwd, MainActivity.this);
        //看看保存成功没
        if(bool)
            Toast.makeText(MainActivity.this, "保存成功！", Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(MainActivity.this, "保存失败！", Toast.LENGTH_SHORT).show();

        try {
            String compeletedURL = HttpUtil.getURLWithParams(originAddress, params);
            HttpUtil.sendHttpRequest(compeletedURL, new HttpCallbackListener() {
                @Override
                public void onFinish(String response) {
                    Message message = new Message();
                    /*JSONObject jsonObject = new JSONObject();
                    JSONObject data;
                    try {
						 data = jsonObject.getJSONObject(response);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}*/
                    message.obj = response;
                    mHandler.sendMessage(message);
                }

                @Override
                public void onError(Exception e) {
                    Message message = new Message();
                    message.obj = e.toString();
                    mHandler.sendMessage(message);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示Toast
     *
     * @param msg 提示信息内容
     */
    private void showToast(int msg) {
        if (null != mToast) {
            mToast.setText(msg);
        } else {
            mToast = Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT);
        }

        mToast.show();
    }
}
